package com.xxkj.drugtraceability.scan

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.xxkj.drugtraceability.base.AppConfig
import com.xxkj.drugtraceability.base.Constants
import com.xxkj.drugtraceability.bean.BarcodeMessage
import com.xxkj.drugtraceability.bean.BarcoderuleBean
import java.net.URLDecoder
import java.util.regex.Pattern

/**
 * Author: mp2
 * Date: 2021/4/21 14:08
 * Describe:
 */


/**
 * barcode匹配规则
 */
var list: List<BarcoderuleBean>? = null
fun readBarcodeRule(): List<BarcoderuleBean>? {
    if (AppConfig.barcode.isNullOrEmpty())
        return emptyList()
    try {
        if (list.isNullOrEmpty()) {
            val turnsType = object : TypeToken<List<BarcoderuleBean>>() {}.type
            list = Gson().fromJson(AppConfig.barcode, turnsType)
        }
    } catch (e: Exception) {

    }
    return list
}

//后台条码规则配置
fun barcodeFormat(barcode: String): BarcodeMessage {
    var message = BarcodeMessage(barcode = barcode)
    val barcodeRules = readBarcodeRule()
    try {
        barcodeRules?.forEach {
                //正则
                    val regex = Regex(URLDecoder.decode(it.regular, "UTF-8"))
                if (barcode.matches(regex)) {
                    //对barcode进行处理
                    var code = barcode
                    message = BarcodeMessage(code, it.barcodetypename)
                    return message
            }
        }
    } catch (e: Exception) {
        return message
    }
    return message
}